<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="贷款还款"
    width="600px"
    @opened="onDialogOpened"
    @closed="onDialogClosed"
  >
    <div class="repayment-content" v-if="loan">
      <div class="loan-summary">
        <h4>贷款信息</h4>
        <div class="summary-info">
          <div class="info-item">
            <span>贷款编号：</span>
            <span>#{{ loan.id }}</span>
          </div>
          <div class="info-item">
            <span>贷款金额：</span>
            <span>¥{{ formatAmount(loan.amount) }}</span>
          </div>
          <div class="info-item">
            <span>剩余本金：</span>
            <span class="highlight">¥{{ formatAmount(loan.remainingPrincipal) }}</span>
          </div>
          <div class="info-item">
            <span>还款方式：</span>
            <span>{{ getRepaymentMethodText(loan.repaymentMethod) }}</span>
          </div>
        </div>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="还款类型" prop="repaymentType">
          <el-radio-group v-model="form.repaymentType">
            <el-radio :label="1">按期还款</el-radio>
            <el-radio :label="2">部分还款</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="还款计划" prop="repaymentPlanId" v-if="form.repaymentType === 1">
          <el-select v-model="form.repaymentPlanId" placeholder="请选择还款期数" style="width: 100%">
            <el-option 
              v-for="plan in availablePlans" 
              :key="plan.id"
              :label="`第${plan.periodNumber}期 - ¥${formatAmount(plan.repaymentAmount)} (${formatDate(plan.repaymentDate)})`"
              :value="plan.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="还款金额" prop="amount">
          <el-input
            v-model="form.amount"
            placeholder="请输入还款金额"
            type="number"
            :min="1"
            ref="amountInputRef"
            :disabled="form.repaymentType === 1"
          >
            <template #append>元</template>
          </el-input>
          <div class="amount-hints">
            <span v-if="form.repaymentType === 1">按期还款金额将自动计算</span>
            <span v-else>最小还款金额：¥100</span>
            <span>账户余额：¥{{ formatAmount(userBalance) }}</span>
          </div>
        </el-form-item>
        
        <el-form-item label="支付密码" prop="paymentPassword">
          <el-input
            v-model="form.paymentPassword"
            type="password"
            placeholder="请输入支付密码"
            maxlength="20"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="confirmRepayment" :loading="loading">
          确认还款
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { getRepaymentPlan } from '@/api/loan';
import { getAccountBalance } from '@/api/account';

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  loan: {
    type: Object,
    default: null
  }
});

const emit = defineEmits(['update:visible', 'confirm']);

// 表单数据
const form = reactive({
  repaymentType: 1, // 1: 按期还款, 2: 部分还款
  repaymentPlanId: '',
  amount: '',
  paymentPassword: ''
});

const formRef = ref(null);
const amountInputRef = ref(null);
const loading = ref(false);
const availablePlans = ref([]);
const userBalance = ref(0);

// 表单验证规则
const rules = {
  repaymentType: [
    { required: true, message: '请选择还款类型', trigger: 'change' }
  ],
  repaymentPlanId: [
    { 
      required: true, 
      message: '请选择还款期数', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.repaymentType === 1 && !value) {
          callback(new Error('请选择还款期数'));
        } else {
          callback();
        }
      }
    }
  ],
  amount: [
    { required: true, message: '请输入还款金额', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入还款金额'));
        } else if (form.repaymentType === 2 && parseFloat(value) < 100) {
          callback(new Error('最小还款金额为¥100'));
        } else if (parseFloat(value) > userBalance.value) {
          callback(new Error(`还款金额不能超过账户余额¥${formatAmount(userBalance.value)}`));
        } else if (form.repaymentType === 2 && parseFloat(value) > (props.loan?.remainingPrincipal || 0)) {
          callback(new Error(`还款金额不能超过剩余本金¥${formatAmount(props.loan?.remainingPrincipal || 0)}`));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
  paymentPassword: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 6, max: 20, message: '支付密码长度在6到20个字符', trigger: 'blur' }
  ]
};

// 工具函数
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

const formatDate = (dateTime) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  return date.toLocaleDateString('zh-CN');
};

const getRepaymentMethodText = (method) => {
  const methodMap = {
    1: '等额本息',
    2: '等额本金',
    3: '一次性还本付息'
  };
  return methodMap[method] || '未知';
};

// 监听还款类型变化
watch(() => form.repaymentType, (newType) => {
  form.repaymentPlanId = '';
  form.amount = '';
  
  if (newType === 1) {
    // 按期还款时禁用金额输入
    if (formRef.value) {
      formRef.value.clearValidate('repaymentPlanId');
    }
  }
});

// 监听还款计划变化
watch(() => form.repaymentPlanId, (planId) => {
  if (planId && form.repaymentType === 1) {
    const selectedPlan = availablePlans.value.find(plan => plan.id === planId);
    if (selectedPlan) {
      form.amount = selectedPlan.repaymentAmount;
    }
  }
});

// 加载还款计划
const loadRepaymentPlans = async () => {
  if (!props.loan) return;
  
  try {
    const response = await getRepaymentPlan(props.loan.id);
    // 只显示未还款的计划
    availablePlans.value = response.data.filter(plan => plan.status === 1) || [];
  } catch (error) {
    console.error('加载还款计划失败：', error);
    ElMessage.error('加载还款计划失败');
  }
};

// 加载用户余额
const loadUserBalance = async () => {
  try {
    const response = await getAccountBalance();
    userBalance.value = response.data.balance || 0;
  } catch (error) {
    console.error('加载账户余额失败：', error);
  }
};

// 弹窗事件处理
const onDialogOpened = () => {
  loadRepaymentPlans();
  loadUserBalance();
  
  // 弹窗打开后自动聚焦
  nextTick(() => {
    if (form.repaymentType === 2 && amountInputRef.value) {
      amountInputRef.value.focus();
    }
  });
};

const onDialogClosed = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.repaymentType = 1;
  form.repaymentPlanId = '';
  form.amount = '';
  form.paymentPassword = '';
  loading.value = false;
  availablePlans.value = [];
};

// 确认还款
const confirmRepayment = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    loading.value = true;
    
    const formData = {
      loanId: props.loan.id,
      repaymentPlanId: form.repaymentType === 1 ? form.repaymentPlanId : undefined,
      amount: parseFloat(form.amount),
      paymentPassword: form.paymentPassword
    };
    
    emit('confirm', formData);
    
  } catch (error) {
    console.error('表单验证失败：', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.repayment-content {
  padding: 8px;
}

.loan-summary {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.loan-summary h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
}

.summary-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  padding: 4px 0;
}

.info-item .highlight {
  color: #e6a23c;
  font-weight: 600;
}

.amount-hints {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .summary-info {
    grid-template-columns: 1fr;
  }
}
</style>
